package com.cxz.kotlin.baselibs.http;

import androidx.annotation.Nullable;

import com.cxz.kotlin.baselibs.bean.BaseBean;
import com.cxz.kotlin.baselibs.utils.LogUtil;
import com.google.gson.Gson;
import com.jinduplan.planmanager.bean.HttpResult;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

final class GsonResponseBodyConverter < T > implements Converter< ResponseBody,
        T > {
    private final Gson gson;
    private final Type type;

    GsonResponseBodyConverter(Gson gson, Type type) {
        this.gson = gson;
        this.type = type;
    }

    /**
     * 针对数据返回成功、错误不同类型字段处理
     */
        @Override
        public T convert(ResponseBody value) throws IOException {
        String response = value.string();
        LogUtil.d("response->"+response);
        try {
            // 这里的type实际类型是 LoginUserEntity<User>  User就是user字段的对象。
            BaseBean result = gson.fromJson(response, BaseBean.class);
            if (result.getCode() != 200) {
                throw new ResultException(result.getMsg(), response,result.getCode());
            } else {
                return  gson.fromJson(response, type);
            }
        } finally {
            value.close();
        }
    }
}

